package zaliapi

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"net/http"
	"strings"

	"gitee.com/zevenfly/goutil/znet"
)

// 创建签名
func createSignature(secret, strToSign string) string {
	key := []byte(secret)
	mac := hmac.New(sha256.New, key)
	mac.Write([]byte(strToSign))
	s := base64.StdEncoding.EncodeToString(mac.Sum(nil))
	return s
}

// HTTP GET 请求
func ApiRequest(url string, appSecret, appKey string) ([]byte, error) {
	bs, err := znet.HttpGetEx(url, func(r *http.Request, data interface{}) error {
		idx := strings.Index(url, r.Host)
		if idx < 0 {
			return fmt.Errorf("url find host error")
		}
		idx += len(r.Host)
		strToSign := "GET\n\n\n\n\n" + url[idx:]
		//fmt.Println("strToSign:", strToSign)
		signature := createSignature(appSecret, strToSign)
		//fmt.Println("signature:", signature)
		r.Header.Add("X-Ca-Signature", signature)
		r.Header.Add("X-Ca-Key", appKey)
		return nil
	}, nil)
	if err != nil {
		return nil, err
	}
	return bs, nil
}

func test() {
	url := "http://xhuabu.market.alicloudapi.com/quote/real?security_code=SZ.399006"
	bs, err := ApiRequest(url, "", "")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(string(bs))
}
